from argparse import REMAINDER
from nonebot import on_shell_command
from typing import Annotated
from nonebot import on_shell_command
from nonebot.exception import ParserExit
from nonebot.params import ShellCommandArgs
from nonebot.rule import Namespace, ArgumentParser
from nonebot.adapters.onebot.v11 import MessageSegment
from nonebot.adapters import Event


import re, requests


parser = ArgumentParser("latex", description='LaTeX 机器人(小灰灰), 使用方法如下:')
parser.add_argument('-q', '--quick', action='store_true')
parser.add_argument('-f', '--full', action='store_true')
parser.add_argument('-u', '--url', action='store_true')
parser.add_argument('-e', '--engine', type=str, default="pdflatex")
parser.add_argument('-p', '--param', type=str, default="", required=True, nargs=REMAINDER)




from .compile import Compile

command = on_shell_command("latex", parser=parser)

@command.handle()
async def _(foo: Annotated[ParserExit, ShellCommandArgs()]):
    await command.finish(foo.message)
    # if foo.status == 0:
    #     await command.finish(foo.message)
    #     print("aaa", foo.message)  # help message
    # else:
    #     print("bbb", foo.message)  # error message

# 解析成功
@command.handle()
async def _(foo: Annotated[Namespace, ShellCommandArgs()], event: Event):
    await command.send(MessageSegment.text("正在编译中，请耐心等待..."))

    arg_dict = vars(foo)

    content = split_by_param(event.get_message().extract_plain_text())
    
    engine = arg_dict['engine']

    if arg_dict['quick']:
        with open("./data/template.tex", "r", encoding="utf-8") as f:
            template = f.read()
            content = template.replace("{{ content }}", content)
        
    elif arg_dict['full']:
        pass
    elif arg_dict['url']:
        content = content.replace('https://pastebin.com/', 'https://pastebin.com/raw/')

        if re.search(r"paste\.ubuntu\.com", content):
            content = content + '/plain'
            headers = {'Host': 'paste.ubuntu.com'}
            cookies = {'sessionid': 'yntnaxqjax6zrqu7ve2vetgxqdb8trh3'}
        else:
            headers = {}
            cookies = {}
        try:

            response = requests.get(content, headers=headers, cookies=cookies)

            response.encoding = 'utf-8'
            response.raise_for_status()  # 检查是否请求成功
        except requests.exceptions.RequestException as e:
            print(f"请求出错: {e}")

        response.raise_for_status()
        content = response.text.replace('\r\n', '\n').replace('\r', '\n')
    else:
        pass


    result = Compile(content, engine).run()
    for item in result:
        await command.send(MessageSegment.image(item))
    await command.finish()
    

def split_by_param(args: str):
    # 找到第一个 -p 或 --param 的位置
    match = re.search(r'(?<!\S)(-p|--param)\s', args)
    if not match:
        return None  # 如果没有找到，返回 None

    # 提取从 -p 或 --param 后的内容
    param_start = match.end()  # 获取匹配结束位置
    return args[param_start:]  # 截取从参数开始到结尾的字符串





